const express = require("express");
const WS_MODULE = require("ws");
const http = require("http");

const app = express();
const port = 8088;

app.get("/websocket/stop", (req, res) => {
    console.log(req, res)
    res.send({
        code: 200,
    });
    clearInterval(intervalId);
});

const server = http.createServer(app);
ws = new WS_MODULE.Server({ server });

ws.on("connection", (conn) => {
    var intervalId = setInterval(() => {
        var data = [
            {
                wxdh: "A1",
                num: '1',
                gzzt: "正在工作",
                tssj: "2023-8-14",
                ywjg: "有",
                jgjb: "1",
            },
            {
                wxdh: "A1",
                num: '3',
                gzzt: "正在工作",
                tssj: "2023-8-14",
                ywjg: "有",
                jgjb: "1",
            },
            { wxdh: "A1", num: '4', gzzt: "正在工作", tssj: "2023-8-14", ywjg: "有", jgjb: "1" },
            {
                wxdh: "A1",
                num: '1',
                gzzt: "正在工作",
                tssj: "2023-8-14",
                ywjg: "有",
                jgjb: "1",
            }]
        for (var i = 0; i < data.length; i++) {
            console.log(i)
            data[i]['num'] = Math.floor(Math.random() * 100 + 1);
        }
        data = JSON.stringify(data)
        conn.send(data, () => {
            console.log('如果说后端想要监听发送状况，能走进来是否意味着发送成功')
        });
        console.log('conn.readyState', conn.readyState)   //ws状态
    }, 1000)

    conn.on("close", function (code, reason) {
        console.log("服务端监听到关闭连接.")
        clearInterval(intervalId);
    });

    conn.on("error", function (code, reason) {
        console.log("服务端监听到连接失败.")
    });

    conn.on("pong", function (res) {
        console.log(res)
    })
    conn.on("message", (str) => {
        //handle received message
    });
});

server.listen(port, () => {
    console.log("服务器已开启，端口号：" + port);
});
